package com.h3bpm.handler;

import OThinker.Common.Organization.Models.User;
import OThinker.H3.Entity.EventHandlers.ICirculateItemEventHandler;
import OThinker.H3.Entity.IEngine;
import OThinker.H3.Entity.WorkItem.CirculateModels.CirculateItem;
import OThinker.H3.Entity.WorkItem.WorkItemState;
import data.DataRow;
import data.DataTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

import java.util.List;

public class CirculateItemHandler implements ICirculateItemEventHandler {
    private static final Logger logger = LoggerFactory.getLogger(CirculateItemHandler.class);

    @Override
    public void OnCreated(IEngine engine, CirculateItem item) {
        logger.info("《》《》《》《》《》《》《》《》@待阅 OnCreated {}, ObjectID={}, status {}", item.toString(), item.getObjectID(), item.getState());
        try {
            String receiver = ((User) engine.getOrganization().GetUnit(item.getParticipant())).getCode();
            logger.info("《》《》《》@待阅 OnCreated receiver={}",receiver );
            PushToPortal.pushCirculateItemToPortal(engine, item, receiver);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    @Override
    public void OnUpdated(IEngine engine, CirculateItem item) {
        logger.info("《》《》《》《》《》《》《》《》@待阅 OnUpdated {}, ObjectID={}, status {}", item.toString(), item.getObjectID(), item.getState());
        try {
            String receiver = ((User) engine.getOrganization().GetUnit(item.getParticipant())).getCode();
            logger.info("《》《》《》@待阅 OnUpdated receiver={}",receiver );
            PushToPortal.pushCirculateItemToPortal(engine, item, receiver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void OnRemoved(IEngine engine, String ObjectID) throws Exception {
        logger.info("任务移除事件 待阅 OnRemoved==========String ObjectID=========="+ObjectID);
        String selectSql = "select Participant,WorkflowCode from ot_circulateitem where ObjectID = '%s'";
        DataTable table = engine.getQuery().QueryTable(String.format(selectSql, ObjectID));
        List<DataRow> entityRows = table.getEntityRows();
        if(!CollectionUtils.isEmpty(entityRows)){
            String participant = entityRows.get(0).getString("Participant");
            String workflowCode = entityRows.get(0).getString("WorkflowCode");
            //已办推送
            PushToPortal.pushFinishToPortal(engine, "1", ObjectID, participant, WorkItemState.Finished, workflowCode);
        }
    }
}
